package com.tpod.taxi;

import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;

public class APIAccessAddressBuilder{
	
	private String hostname;
	private String router;
	private String params="";
	
	public APIAccessAddressBuilder(String hostname,String router) {		
		this(hostname, router,"default", null);
	}

	public APIAccessAddressBuilder(String hostname,String router,String action) {		
		this(hostname, router,action, null);
	}
	
	public APIAccessAddressBuilder(String hostname,String router,String action,HashMap<String, String> params) {		
		this.hostname = hostname.startsWith("http://")?hostname:"http://"+hostname;
		this.router = (new StringBuilder("?r=")).append(router).append("/").append(action).toString();
		if(params!=null){
			Iterator<Entry<String, String>> iter = params.entrySet().iterator();
			while (iter.hasNext()) {
				Entry<String, String> mEntry = iter.next();
				this.params+=(new StringBuilder()).append("&").append(mEntry.getKey()).append("=").append(mEntry.getValue()).toString();
			}
		}
		
	}

	
	public String getURL(){
		String urlStr = (new StringBuilder()).append(hostname).append(router).append(params).toString();
		try {
			URL url = new URL(urlStr);	
			URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef());
			return uri.toURL().toString();
		} catch (MalformedURLException e) {			
			e.printStackTrace();
		} catch (URISyntaxException e) {
			e.printStackTrace();
		}		
		return urlStr;

	}
	
	

}
